<?php
namespace Common;

use Think\Model\RelationModel;
use Think\Page;

class User extends RelationModel
{
	
	protected $tableName = 'users';
	
	
	/*
	*登录
	*/
	public function login($username,$password,$remember = null){
		$result = array();
		
		$user = M('users')->where("user_name='{$username}'")->find();
		
		if($user['user_id'] > 0){
			if(!empty($user['ec_salt'])){
				$password_attr =  md5(md5($password).$user['ec_salt']);
				
				if($password_attr != $user['password']){
					$result['status'] = 0;
					$result['msg'] = "密码错误";
					return $result;
				}
			}else{
				$password_attr =  md5($password);
				
				if($password_attr != $user['password']){
					$result['status'] = 0;
					$result['msg'] = "密码错误";
					return $result;
				}
				
				$ec_salt = rand(1, 9999);
				
				$password_attr  = md5(md5($password).$ec_salt);
				
				M('users')->where("user_id = {$user['user_id']}")->save(array('ec_salt'=>$ec_salt,'password'=>$password_attr));
			}
			
			//记录本次登录ip和时间
			$ip = get_client_ip();
			$reg_date = time();
			M('users')->where("user_id = {$user['user_id']}")->save(array('last_login'=>$reg_date,'last_ip'=>$ip));
			
			session('user_id',$user['user_id']);
			session('user_name',$user['user_name']);
			
			//记住密码
			if($remember == 1){
				setcookie('nhs[user_id]',$user['user_id']);
				setcookie('nhs[password]',$password_attr);
			}
			
			$result['status'] = 1;
			$result['msg'] = "登录成功";
			return $result;
		}else{
			$result['status'] = 0;
			$result['msg'] = "账号不存在";
			return $result;
		}
		
	}
	
	
	/*
	*检查用户名
	*/
	public function check_user_name($username){
		$have_user = M('users')->where("user_name='{$username}'")->count();
        return $have_user;
	}
	
	/*
	*
	*/
	public function logout(){
		setcookie('nhs[user_id]',"");
		setcookie('nhs[password]',"");
		unset($_SESSION['user_id']);
		unset($_SESSION['user_name']);
	}

	/*
	*检验自动登录
	*/
	public function autoLogin(){
		if(empty($_SESSION['user_id']) && !empty($_COOKIE['nhs']['user_id'])){echo 123;exit;
			$user_id = $_COOKIE['nhs']['user_id'];
			$user_password = $_COOKIE['nhs']['password'];
			
			$user = M('users')->where("user_id='{$user_id}' AND password = '{$user_password}'")->count();
			
			if($user > 0){
				$_SESSION['user_id'] = $user_id;
			}
			
		}
	}
	
}
?>